<template>
  <van-form @submit="onSubmit">
    <van-field
        v-if="editUser.editName != '性别'"
        v-model="editUser.currentValue"
        :name="editUser.editKey"
        :label="editUser.editName"
        :placeholder="'请输入${editUser.editName}'"
    />
    <van-field name="radio" label="性别" v-if="editUser.editName === '性别'">
      <template #input>
        <van-radio-group v-model="editUser.currentValue" direction="horizontal">
          <van-radio name="男">男</van-radio>
          <van-radio name="女">女</van-radio>
        </van-radio-group>
      </template>
    </van-field>
    <div style="margin: 16px;">
      <van-button round block type="primary" native-type="submit">
        提交
      </van-button>
    </div>
  </van-form>
</template>

<script setup lang="ts">
import {useRoute, useRouter} from "vue-router";
import {onMounted, ref} from "vue";
import myAxios from "../plugins/myAxios";
import {showFailToast, showSuccessToast} from "vant";
import {getCurrentUser} from "../services/user";

const route = useRoute();
const router =useRouter();

const editUser = ref({
  editKey: route.query.editKey,
  currentValue: route.query.currentValue,
  editName: route.query.editName,
})
console.log("editUser.value.currentValue== " + editUser.value.currentValue)
// const gender = ref(editUser.value.currentValue === '男'?'0':'1');

// 不可以写在外面，否则页面不显示内容，还没有报错信息，原因未知
// const currentUser = await getCurrentUser();

const onSubmit = async () => {
  // 异步方法必须添加 await 才可以拿到数据, 否则拿到的是 promise 对象
  const currentUser = await getCurrentUser();
  if (editUser.value.currentValue === "男"){
    editUser.value.currentValue = '0';
  }
  if (editUser.value.currentValue === "女"){
    editUser.value.currentValue = '1';
  }
  const res = await myAxios.post("/user/update", {
    "id": currentUser.id,
    [editUser.value.editKey as string]: editUser.value.currentValue // 动态取值
  })
  console.log("修改用户信息", res);
  if (res.code == 0 && res.data > 0) {
    showSuccessToast("修改成功");
    router.replace("/user");
  } else {
    showFailToast("修改失败");
  }
};

</script>

<style scoped>

</style>